package com.gridmobi.xrtb.handler.impl;


import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Sets;
import com.gridmobi.xrtb.domain.dsp.DspCreativeBanner;
import com.gridmobi.xrtb.domain.dsp.DspCreativeHtml;
import com.gridmobi.xrtb.domain.dsp.DspCreativeNative;
import com.gridmobi.xrtb.domain.dsp.DspCreativeVideo;
import com.gridmobi.xrtb.domain.dsp.common.AppConstant;
import com.gridmobi.xrtb.domain.dsp.common.OpenApiParamDTO;
import com.gridmobi.xrtb.domain.dsp.common.OpenApiResponseDTO;
import com.gridmobi.xrtb.domain.dsp.common.enums.CreativeTypeE;
import com.gridmobi.xrtb.handler.DataSynchHandler;
import com.gridmobi.xrtb.handler.monitor.RtbStatus;
import com.gridmobi.xrtb.handler.monitor.SimpleData;
import com.gridmobi.xrtb.job.SourceManager;
import com.gridmobi.xrtb.model.rtb.Creative;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class DataSynchHandlerImpl implements DataSynchHandler {
    private static final Logger logger = LoggerFactory.getLogger(DataSynchHandlerImpl.class);

    @Value("${datasynch.url.cfglist}")
    private String cfglistUrl;

    @Value("${datasynch.url.campaigns}")
    private String campaignstUrl;

    @Value("${datasynch.url.banners}")
    private String bannerstUrl;
    @Value("${datasynch.url.videos}")
    private String videostUrl;
    @Value("${datasynch.url.htmls}")
    private String htmlstUrl;
    @Value("${datasynch.url.natives}")
    private String nativesUrl;
    @Value("${datasynch.url.campaigntrend}")
    private String ctrendUrl;
    @Value("${datasynch.url.microbid}")
    private String microbidUrl;
    @Value("${datasynch.url.rules}")
    private String rulesUrl;

    @Value("${datasynch.url.blocklist}")
    private String blocklistUrl;

    @Value("${img.url.prefix}")
    private String imageUrlPrefix;

    @Value("${ori.cdn.domain}")
    private String oriCdnDomain;
    @Value("${datasynch.url.offersUrl}")
    private String offersUrl;
    @Autowired
    private RestTemplate restTemplate;


    @Autowired
    private SysError sysError;

    @Autowired
    SourceManager sourceManager;

    @Override
    public Map<String, Map<String, Map>> synchCampaignTrend() {
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<OpenApiParamDTO> entity = new HttpEntity<OpenApiParamDTO>(headers);
            HttpEntity<Map> response = restTemplate.exchange(ctrendUrl, HttpMethod.POST, entity, Map.class);
            SysError.DATA_SYNCH_ERROR_TIMES.set(0);

            return response.getBody();
        } catch (RestClientException e) {
            e.printStackTrace();
            sysError.datasynchError(e);
        }
        return null;


    }


    @Override
    public OpenApiResponseDTO synchCampaigns(OpenApiParamDTO param) {
        try {
            SimpleData.BUDGET_ACTI_CAMPAIGN = Sets.newHashSet();
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<OpenApiParamDTO> entity = new HttpEntity<OpenApiParamDTO>(null, headers);
//            logger.info("synchCampaigns:"+JSONObject.toJSONString(new OpenApiParamDTO()));

            HttpEntity<OpenApiResponseDTO> response = restTemplate.exchange(campaignstUrl, HttpMethod.POST, entity, OpenApiResponseDTO.class);
            if (response.getBody() != null) {
                logger.info("synchCampaigns:"+JSONObject.toJSONString(response.getBody()));
            }
            if (CollectionUtils.isEmpty(response.getBody().getDatas())) {
                RtbStatus.BID_LOCK = true;

            } else {
                RtbStatus.BID_LOCK = false;

            }
            SysError.DATA_SYNCH_ERROR_TIMES.set(0);

            return response.getBody();
        } catch (Exception e) {
            e.printStackTrace();
            sysError.datasynchError(e);
            RtbStatus.BID_LOCK = true;
        }
        return null;


    }

    @Override
    public OpenApiResponseDTO synchCfg(OpenApiParamDTO param) {
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<OpenApiParamDTO> entity = new HttpEntity<OpenApiParamDTO>(null, headers);
            HttpEntity<OpenApiResponseDTO> response = restTemplate.exchange(cfglistUrl, HttpMethod.POST, entity, OpenApiResponseDTO.class);
            SysError.DATA_SYNCH_ERROR_TIMES.set(0);

            return response.getBody();
        } catch (RestClientException e) {
            e.printStackTrace();
            sysError.datasynchError(e);

        }
        return null;

    }

    @Override
    public List<DspCreativeBanner> synchCreativeBanner(OpenApiParamDTO param) {
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<OpenApiParamDTO> entity = new HttpEntity<OpenApiParamDTO>(null, headers);
            HttpEntity<OpenApiResponseDTO> response = restTemplate.exchange(bannerstUrl, HttpMethod.POST, entity, OpenApiResponseDTO.class);
            if (response.getBody() != null && response.getBody().getDatas() != null) {
                List<HashMap> list = response.getBody().getDatas();
                return list.stream().map(n -> {
                    return JSONObject.parseObject(JSONObject.toJSONString(n), DspCreativeBanner.class);
                }).collect(Collectors.toList());

            }
            SysError.DATA_SYNCH_ERROR_TIMES.set(0);

        } catch (RestClientException e) {
            e.printStackTrace();
            sysError.datasynchError(e);
        }
        return null;
    }

    @Override
    public List<DspCreativeVideo> synchCreativeVideo(OpenApiParamDTO param) {
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<OpenApiParamDTO> entity = new HttpEntity<OpenApiParamDTO>(null, headers);
            HttpEntity<OpenApiResponseDTO> response = restTemplate.exchange(videostUrl, HttpMethod.POST, entity, OpenApiResponseDTO.class);
            if (response.getBody() != null && response.getBody().getDatas() != null) {
                List<HashMap> list = response.getBody().getDatas();
                return list.stream().map(n -> {
                    return JSONObject.parseObject(JSONObject.toJSONString(n), DspCreativeVideo.class);
                }).collect(Collectors.toList());

            }

            SysError.DATA_SYNCH_ERROR_TIMES.set(0);

        } catch (RestClientException e) {
            e.printStackTrace();
            sysError.datasynchError(e);

        }
        return null;
    }

    @Override
    public List<DspCreativeHtml> synchCreativeHtml(OpenApiParamDTO param) {
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<OpenApiParamDTO> entity = new HttpEntity<OpenApiParamDTO>(null, headers);
            HttpEntity<OpenApiResponseDTO> response = restTemplate.exchange(htmlstUrl, HttpMethod.POST, entity, OpenApiResponseDTO.class);
            if (response.getBody() != null && response.getBody().getDatas() != null) {
                List<HashMap> list = response.getBody().getDatas();
                return list.stream().map(n -> {
                    return JSONObject.parseObject(JSONObject.toJSONString(n), DspCreativeHtml.class);
                }).collect(Collectors.toList());

            }
            SysError.DATA_SYNCH_ERROR_TIMES.set(0);

        } catch (RestClientException e) {

            e.printStackTrace();
            sysError.datasynchError(e);
        }
        return null;
    }

    @Override
    public List<DspCreativeNative> synchCreativeNative(OpenApiParamDTO param) {
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<OpenApiParamDTO> entity = new HttpEntity<OpenApiParamDTO>(null, headers);
            HttpEntity<OpenApiResponseDTO> response = restTemplate.exchange(nativesUrl, HttpMethod.POST, entity, OpenApiResponseDTO.class);
            if (response.getBody() != null && response.getBody().getDatas() != null) {
                List<HashMap> list = response.getBody().getDatas();
                return list.stream().map(n -> {
                    return JSONObject.parseObject(JSONObject.toJSONString(n), DspCreativeNative.class);
                }).collect(Collectors.toList());
            }
            SysError.DATA_SYNCH_ERROR_TIMES.set(0);

        } catch (RestClientException e) {

            e.printStackTrace();
            sysError.datasynchError(e);
        }
        return null;
    }

    public void convertNativeList(List<DspCreativeNative> list) {
        if (CollectionUtils.isEmpty(list)) {
            return ;
        }
    }

    @Override
    public List<Creative> convertBannerList(List<DspCreativeBanner> list) {
        if (CollectionUtils.isEmpty(list)) {
            return new LinkedList<Creative>();
        }
        return list.stream().map(o -> {

            DspCreativeBanner n = JSONObject.parseObject(JSONObject.toJSONString(o), DspCreativeBanner.class);
            Creative creative = new Creative();

            creative.setId(CreativeTypeE.BANNER.code + AppConstant.URL_SEPARATOR + n.getId());
            creative.setAid(n.getAid());
            creative.setCids(n.getCids());
            creative.setDeleteflag(n.getDeleteflag());
            creative.setState(n.getState());
            creative.setH(n.getH());
            creative.setW(n.getW());
            creative.setMime(n.getMimes());
            if (StringUtils.isBlank(creative.getMime())) {
                creative.setMime("image/png");
            }
            creative.setType(CreativeTypeE.BANNER.code);
            //替换image url前缀

            if (n.getWeburl() != null && n.getWeburl().contains(oriCdnDomain)) {
                n.setWeburl(n.getWeburl().replace(oriCdnDomain, imageUrlPrefix));
            }
            creative.setUrl(n.getWeburl());
            return creative;
        }).collect(Collectors.toList());
    }

    @Override
    public List<Creative> convertVideoList(List<DspCreativeVideo> list) {
        if (CollectionUtils.isEmpty(list)) {
            return new LinkedList<Creative>();
        }
        return list.stream().map(n -> {
            Creative creative = new Creative();
            creative.setId(CreativeTypeE.VIDEO.code + AppConstant.URL_SEPARATOR + n.getId());
            creative.setAid(n.getAid());
            creative.setCids(n.getCids());
            creative.setDeleteflag(n.getDeleteflag());
            creative.setState(n.getState());
            creative.setH(n.getH());
            creative.setW(n.getW());
            creative.setBsize(n.getBsize());
            creative.setVideoduration(n.getMinduration());
            creative.setMime(n.getMimes());
            if (StringUtils.isBlank(creative.getMime())) {
                creative.setMime("video/mp4");
            }
            creative.setType(CreativeTypeE.VIDEO.code);
            creative.setUrl(n.getWeburl());
            return creative;
        }).collect(Collectors.toList());
    }

    @Override
    public List<Creative> convertHtmlList(List<DspCreativeHtml> list) {
        if (CollectionUtils.isEmpty(list)) {
            return new LinkedList<Creative>();
        }
        return list.stream().map(n -> {
            Creative creative = new Creative();
            creative.setId(CreativeTypeE.HTML.code + AppConstant.URL_SEPARATOR + n.getId());
            creative.setAid(n.getAid());
            creative.setCids(n.getCids());
            creative.setDeleteflag(n.getDeleteflag());
            creative.setState(n.getState());
            creative.setH(n.getH());
            creative.setW(n.getW());
            creative.setMime(n.getMimes());
            if (StringUtils.isBlank(creative.getMime())) {
                creative.setMime("application/javascript");
            }
            creative.setType(CreativeTypeE.HTML.code);
            creative.setVideoduration(n.getVideoduration());
            SimpleData.RICH_MEDIA.put(creative.getId(), new String(n.getScriptcontent()));
            return creative;
        }).collect(Collectors.toList());
    }


    @Override
    public OpenApiResponseDTO synchMicroBid(OpenApiParamDTO param) {
        try {
            logger.info("synchMicroBid:" + JSONObject.toJSONString(param));

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<OpenApiParamDTO> entity = new HttpEntity<OpenApiParamDTO>(null, headers);
            HttpEntity<OpenApiResponseDTO> response = restTemplate.exchange(microbidUrl, HttpMethod.POST, entity, OpenApiResponseDTO.class);
            if (response.getBody() != null) {
                logger.info(JSONObject.toJSONString(response.getBody()));
            }
            SysError.DATA_SYNCH_ERROR_TIMES.set(0);
            return response.getBody();
        } catch (RestClientException e) {
            e.printStackTrace();
            sysError.datasynchError(e);

        }
        return null;

    }


    @Override
    public OpenApiResponseDTO synchBlocklist(OpenApiParamDTO param) {
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<OpenApiParamDTO> entity = new HttpEntity<OpenApiParamDTO>(null, headers);
            HttpEntity<OpenApiResponseDTO> response = restTemplate.exchange(blocklistUrl, HttpMethod.POST, entity, OpenApiResponseDTO.class);
            SysError.DATA_SYNCH_ERROR_TIMES.set(0);
            return response.getBody();
        } catch (RestClientException e) {
            e.printStackTrace();
        }
        return null;

    }


    @Override
    public OpenApiResponseDTO synchRules(OpenApiParamDTO param) {
        logger.info("synchRules:" + JSONObject.toJSONString(param));

        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<OpenApiParamDTO> entity = new HttpEntity<OpenApiParamDTO>(null, headers);
            HttpEntity<OpenApiResponseDTO> response = restTemplate.exchange(rulesUrl, HttpMethod.POST, entity, OpenApiResponseDTO.class);
            if (response.getBody() != null) {
                logger.info(JSONObject.toJSONString(response.getBody()));
            }
            SysError.DATA_SYNCH_ERROR_TIMES.set(0);
            return response.getBody();
        } catch (RestClientException e) {
            e.printStackTrace();
            sysError.datasynchError(e);

        }
        return null;
    }

    @Override
    public OpenApiResponseDTO synchOffers(OpenApiParamDTO param) {
        logger.info("synchOffers:" + JSONObject.toJSONString(param));
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<OpenApiParamDTO> entity = new HttpEntity<OpenApiParamDTO>(null, headers);
            HttpEntity<OpenApiResponseDTO> response = restTemplate.exchange(offersUrl, HttpMethod.POST, entity, OpenApiResponseDTO.class);
            if (response.getBody() != null) {
                logger.info(JSONObject.toJSONString(response.getBody()));
                return response.getBody();
            }
            SysError.DATA_SYNCH_ERROR_TIMES.set(0);
            return response.getBody();
        } catch (RestClientException e) {
            e.printStackTrace();
            sysError.datasynchError(e);

        }
        return null;
    }
}
